﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Net;
using System.IO;
namespace huaguwang
{
    public class D_T_StockCode_Exp : D_T_StockCode
    {

        /// <summary>
        /// 获取记录总条数 
        /// </summary>
        public int GetOneTablePageCount(string name, string code)
        {
            var wherestring = string.Empty;
            if ("" != name)
            {
                wherestring += "and title = @name";
            }
            if ("" != code)
            {
                wherestring += "and code = @code";
            }
            SqlParameter[] parameters = {
					new SqlParameter("@name",SqlDbType.NVarChar,20),
					new SqlParameter("@code", SqlDbType.NVarChar,10)};
            parameters[0].Value = name;
            parameters[1].Value = code;
            return GetOneTablePageCount(wherestring, parameters);
        }
        /// <summary>
        /// 翻页信息显示
        /// </summary>
        /// <param name="Begin"></param>
        /// <param name="Page"></param>
        /// <param name="name"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public List<huaguwang.M_T_StockCode> GetOneTablePage(int Begin, int Page, string name, string code)
        {

            var wherestring = string.Empty;
            if ("" != name)
            {
                wherestring += "and title = @name";
            }
            if ("" != code)
            {
                wherestring += "and code = @code";
            }
            SqlParameter[] parameters = {
					new SqlParameter("@name",SqlDbType.NVarChar,20),
					new SqlParameter("@code", SqlDbType.NVarChar,10)};
            parameters[0].Value = name;
            parameters[1].Value = code;
            return GetOneTablePage(Begin, Page, wherestring, parameters);
        }


        private string ReturnGu_code(string code)
        {
            if (code.Exp_Left(2) == "00")
            {
                return "sz" + code;
            }
            else
            {
                return "sh" + code;
            }
        }
        /// <summary>
        /// 获取接口数据返回数组
        /// </summary>
        /// <param name="_gustring">股票代码</param>
        /// <returns></returns>
        private string[] GetGuCode(string _gustring)
        {
            _gustring = ReturnGuList(_gustring);
            if (_gustring.Contains(","))
            {
                int start = 0;
                start = _gustring.IndexOf("\"");
                _gustring = _gustring.Substring(start + 1, _gustring.IndexOf("\"", start + 1) - start - 1).ToString();
                string[] _gucode = _gustring.Split(',');
                return _gucode;
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 获取新浪股票接口代码
        /// </summary>
        /// <param name="gucode">股票代码</param>
        /// <returns></returns>
        public string ReturnGuList(string gucode)
        {
            WebRequest wrq;
            HttpWebResponse wrp;

            wrq = HttpWebRequest.Create("http://hq.sinajs.cn/list=" + gucode);
            wrp = (HttpWebResponse)wrq.GetResponse();
            Stream resStream = wrp.GetResponseStream();
            StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
            string tempstr = sr.ReadToEnd();
            return tempstr;
        }
        //_hr.Url = "http://hq.sinajs.cn/list=sh601006";
        //_hr.ToString();
        //"http://hq.sinajs.cn/list=sh601006";
        //WebRequest request = WebRequest.Create("http://www.baidu.com");//
        //var hq_str_sh601006=\"大秦铁路,8.04,8.05,8.01,8.06,8.00,8.01,8.02,23526793,188687354,245781,8.01,2400432,8.00,897600,7.99,1368800,7.98,522400,7.97,456753,8.02,97920,8.03,113100,8.04,209170,8.05,126246,8.06,2010-12-23,11:35:55\";\n"
        //0：”大秦铁路”，股票名字； 
        //1：”27.55″，今日开盘价； 
        //2：”27.25″，昨日收盘价； 
        //3：”26.91″，当前价格； 
        //4：”27.55″，今日最高价； 
        //5：”26.20″，今日最低价； 
        //6：”26.91″，竞买价，即“买一”报价； 
        //7：”26.92″，竞卖价，即“卖一”报价； 
        //8：”22114263″，成交的股票数，由于股票交易以一百股为基本单位，所以在使用时，通常把该值除以一百； 
        //9：”589824680″，成交金额，单位为“元”，为了一目了然，通常以“万元”为成交金额的单位，所以通常把该值除以一万； 
        //10：”4695″，“买一”申请4695股，即47手； 
        //11：”26.91″，“买一”报价； 
        //12：”57590″，“买二” 
        //13：”26.90″，“买二” 
        //14：”14700″，“买三” 
        //15：”26.89″，“买三” 
        //16：”14300″，“买四” 
        //17：”26.88″，“买四” 
        //18：”15100″，“买五” 
        //19：”26.87″，“买五” 
        //20：”3100″，“卖一”申报3100股，即31手； 
        //21：”26.92″，“卖一”报价 
        //(22, 23), (24, 25), (26,27), (28, 29)分别为“卖二”至“卖四的情况” 
        //30：”2008-01-11″，日期； 
        //31：”15:05:32″，时间； 
        /// <summary>
        /// 获取最新股票信息
        /// </summary>
        /// <param name="errorstring">错误提示</param>
        /// <returns></returns>
        public bool ExcuteGetGuInfo(out string errorstring)
        {
            if (DateTime.Now.Hour > 17 && DateTime.Now.Minute > 5)
            {
                errorstring = "对不起，不能在规定时间外更新，请联系管理员!";
                return false;
            }
            var sql = string.Empty;
            string[] _tt = null;
            sql = "select top 1 code,title from T_StockCode";
            DataSet ds = MSSQLHelper.SQLConType.C1.Exp_Query(sql);
            if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
            {
                _tt = GetGuCode(ReturnGu_code(ds.Tables[0].Rows[0]["code"].ToString()));
                sql = "select stockcode from T_StockExchange  where convert(nvarchar(10),exchdate,120)='" + _tt[30].ToString() + "'";
                ds = MSSQLHelper.SQLConType.C1.Exp_Query(sql);
                if (ds.Tables[0] == null || ds.Tables[0].Rows.Count <= 0)
                {
                    sql = "select id,code,title from T_StockCode where id<5";
                    DataTable _dt = new DataTable();
                    _dt = MSSQLHelper.SQLConType.C1.Exp_Query(sql).Tables[0];
                    StringBuilder _sb = new StringBuilder();
                    foreach (DataRow dr in _dt.Rows)
                    {
                        _tt = GetGuCode(ReturnGu_code(dr["code"].ToString()));
                        if (_tt != null)
                        {
                            _sb.Append(" insert into T_StockExchange (stockcode,realcode,price,exchdate,flag,yesprice)" +
                            "values ('" + dr["code"].ToString() + "','" + dr["id"].ToString() + "'," + _tt[3].ToString() + ",'" + _tt[30].ToString() + " " + _tt[31].ToString() + "',1," + _tt[2].ToString() + ")");
                        }
                    }
                    if (_sb.ToString() != "")
                    {
                        _sb.Insert(0, "begin tran ");
                        _sb.Append(" if @@error<>0 ");
                        _sb.Append("rollback tran ");
                        _sb.Append("commit tran ");
                        try
                        {
                            MSSQLHelper.SQLConType.C1.Exp_ExecuteSql(_sb.ToString());
                            errorstring = "操作成功，谢谢!";
                            return true;
                        }
                        catch (Exception ex)
                        {
                            errorstring = "执行失败，" + ex + "谢谢!";
                            return false;
                        }
                    }
                    else
                    {
                        errorstring = "无程序执行，谢谢!";
                        return false;
                    }

                }
                else
                {
                    errorstring = "对不起，同一天请不要重复更新，谢谢!";
                    return false;
                }
            }
            else
            {
                errorstring = "对不起，数据库无股票代码，请联系管理员，谢谢!";
                return false;
            }
        }

        /// <summary>
        /// 执行搏股和搏股跟随计算
        /// </summary>
        /// <param name="userid">操作人ID</param>
        /// <param name="errorstring">错误提示</param>
        public void ExcuteAccountBoGuInfo(int userid, out DataTable datatable)
        {
            var sql = string.Empty;
            sql = "select id,title from T_WinStock where convert(nvarchar(10),betdate,120)=convert(nvarchar(10),getdate(),120) and flag=1 and issetscore=0";
            DataSet ds = MSSQLHelper.SQLConType.C1.Exp_Query(sql);
            DataTable _dt = new DataTable();
            
            _dt.Columns.Add("id",Type.GetType("System.Int32"));
            _dt.Columns.Add("title",Type.GetType("System.String"));
            _dt.Columns.Add("state", Type.GetType("System.Int16"));
            DataTable _dtnew = new DataTable();
            if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow item in ds.Tables[0].Rows)
                {
                    _dtnew = MSSQLHelper.SQLConType.C1.Exp_Query("exec P_AccountBoGu_Value " + item["id"].ToString() + "," + userid).Tables[0];
                    DataRow _dr = _dt.NewRow();
                    _dr["id"] = item["id"].ToString();
                    _dr["title"] = item["title"].ToString();
                    _dr["state"] = _dtnew.Rows[0][0].ToString();
                    _dt.Rows.Add(_dr);
                }
            }
            datatable = _dt.Copy();
        }



    }
}
